<template>
  <d2-container>
    <el-card shadow="never" class="d2-mb">
      <el-form
        class="filter-container"
        ref="marketForm"
        :model="marketForm"
        label-width="85px"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="名称">
              <el-input placeholder="请输入内容" v-model="marketForm.name" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="日期">
               <el-date-picker
                 v-model="marketForm.date"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期">
               </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="来源">
              <el-input placeholder="请输入内容" v-model="marketForm.price_origin" clearable>
              </el-input>
            </el-form-item>
          </el-col>
           <el-col :span="2">
          <el-button type="primary" size="small" @click="handle_marketChange">
            <d2-icon name="search" /> 查询
          </el-button>
        </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="small" @click="addMarket">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-button type="default" size="small" @click="editMarket">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button type="default" size="small" icon="el-icon-delete" @click="delMarket">
        删除
      </el-button>
      <!-- <el-button type="default" size="small" @click="examine">
        <d2-icon name="search" />
        查看
      </el-button> -->
      <el-upload
            class="upload-btn"
            :action="uploadUrl"
            accept=".xls, .xlsx"
            :on-success="handleAvatarSuccess"
            :on-progress="uploadProgress"
            :on-error="handleUploadError"
            :show-file-list="false" style="display:inline-block;margin:0 10px;">
          <el-button type="default" size="small">
            <d2-icon name="download" />
            导入
          </el-button>
          </el-upload>
      <el-button type="default" size="small" @click="handleFormSubmit">
        <d2-icon name="upload" />
        导出
      </el-button>
      <el-button
        type="default"
        size="small"
        @click="handler_efreshCurrent"
      >
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-card shadow="never" class="d2-mb">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">自定义现货行情信息</p>
      </template>
      <el-table
        :data="markettableData"
        border
        :header-cell-style="{ background: '#eef1f6' }"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40"> </el-table-column>
        <el-table-column type="index" label="序号" width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="自定义现货行情名称"
          sortable width="180"
        ></el-table-column>
        <el-table-column prop="date" label="日期" sortable></el-table-column>
        <el-table-column prop="unit" label="价格" sortable></el-table-column>
        <el-table-column
          prop="price_origin"
          label="来源"
          sortable
        ></el-table-column>
      </el-table>
    </el-card>
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange1"
      background
      :current-page="marketForm.currentPage"
      :page-size="marketForm.pageSize"
      layout="total, prev, pager, next"
      :total="marketForm.totalPage"
    >
    </el-pagination>
    <!-- 新增 -->
    <el-dialog :visible.sync="marketVisible" v-if="marketVisible" title="自定义现货行情-新增">
       <div>
    <div class="mb">
       <el-button type="default" size="small" @click="addRow">
        <d2-icon name="plus"/>
        增行
      </el-button>
      <el-button type="default" size="small" icon="el-icon-delete" @click="delData">
        删行
      </el-button>
    </div>
    <el-form label-position="right" status-icon :rules="rules" :model="add_markettableData" ref="ruleForm">
    <el-table :data="add_markettableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
       <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column label="自定义现货行情名称" sortable width="180">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input placeholder="请输入内容" v-model="scope.row.name"></el-input>
           </el-form-item>
        </template>
        </el-table-column>
      <el-table-column label="日期" sortable width="160">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.date'" :rules="rules.date">
          <el-date-picker
                 v-model="scope.row.date"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期" style="width:100%;padding-right:0;">
               </el-date-picker>
                </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="价格" sortable width="100">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price'" :rules="rules.price">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.price"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
       <el-table-column label="单位" sortable width="200">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price_unit'" :rules="rules.price_unit">
           <el-select  clearable v-model="scope.row.price_unit" placeholder="请选择" filterable allow-create>
                <el-option label="元（人民币）/吨" value="元（人民币）/吨"></el-option>
               <el-option label="元（人民币）/千克" value="元（人民币）/千克"></el-option>
               <el-option label="元（人民币）/桶" value="元（人民币）/桶"></el-option>     
               <el-option label="元（人民币）/立方米" value="元（人民币）/立方米"></el-option>
               <el-option label="元（人民币）/张" value="元（人民币）/张"></el-option>
               <el-option label="元（人民币）/克" value="元（人民币）/克"></el-option>
               <el-option label="元（人民币）/500千克" value="元（人民币）/500千克"></el-option>
			     </el-select>
          </el-form-item>
         </template>
         </el-table-column>
      <el-table-column label="来源" sortable>
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price_origin'" :rules="rules.price_origin">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.price_origin"
          ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
    </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="marketVisible = false">取消</el-button>
        <el-button type="primary" @click="addMarketChange('ruleForm')">保存</el-button
        >
      </span>
    </el-dialog>
     <!-- 修改 -->
    <el-dialog :visible.sync="edit_marketVisible" v-if="edit_marketVisible" title="自定义现货行情-修改">
       <div>
         <el-form label-position="right" status-icon :rules="rules" :model="edit_markettableData" ref="ruleForm">
    <el-table :data="edit_markettableData" border>
      <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column label="自定义现货行情名称" sortable width="180">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.name"
          ></el-input>
           </el-form-item>
        </template>
        </el-table-column>
      <el-table-column label="日期" sortable width="160">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.date'" :rules="rules.date">
          <el-date-picker
                 v-model="scope.row.date"
                 type="date" style="width:100%;padding-right:0;"
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期">
               </el-date-picker>
                </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="价格" sortable width="100">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price'" :rules="rules.price">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.price"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
       <el-table-column label="单位" sortable width="200">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price_unit'" :rules="rules.price_unit">
           <el-select  clearable v-model="scope.row.price_unit" placeholder="请选择" filterable allow-create>
               <el-option label="元（人民币）/吨" value="元（人民币）/吨"></el-option>
               <el-option label="元（人民币）/千克" value="元（人民币）/千克"></el-option>
               <el-option label="元（人民币）/桶" value="元（人民币）/桶"></el-option>     
               <el-option label="元（人民币）/立方米" value="元（人民币）/立方米"></el-option>
               <el-option label="元（人民币）/张" value="元（人民币）/张"></el-option>
               <el-option label="元（人民币）/克" value="元（人民币）/克"></el-option>
               <el-option label="元（人民币）/500千克" value="元（人民币）/500千克"></el-option>
			     </el-select>
          </el-form-item>
         </template>
         </el-table-column>
      <el-table-column label="来源" sortable>
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.price_origin'" :rules="rules.price_origin">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.price_origin"
          ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
     </el-table>
    </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="edit_marketVisible = false">取消</el-button>
        <el-button type="primary" @click="editMarketChange('ruleForm')">保存</el-button
        >
      </span>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog :visible.sync="drmarketVisible" v-if="drmarketVisible" title="导入自定义现货行情">
       <div>
    <el-table :data="drmarkettableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
       <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column label="自定义现货行情名称" prop="name">
        </el-table-column>
      <el-table-column label="日期" prop="date">
      </el-table-column>
      <el-table-column label="价格" prop="price">
      </el-table-column>
      <el-table-column label="单位" prop="price_unit">
      </el-table-column>
      <el-table-column label="来源" prop="price_origin">
      </el-table-column>
    </el-table>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="drmarketVisible = false">取消</el-button>
        <el-button type="primary" @click="drmarket">导入数据</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import DemoPageFooter from "../../../components/PageFooter";
import { conmarket, addmarket } from '../../../api/url_lcc';
export default {
  //自定义现货行情
  name: "custom_spot_market",
  components: {
    "demo-page-footer": DemoPageFooter,
  },
  data() {
    return {
      uploadUrl:`/user/lead/`,
      drmarketVisible: false,
      drmarkettableData:[],
      marketVisible: false,
      edit_marketVisible: false,
      marketForm: {
        page: 1, //当前页
        pageSize: 20,
        totalPage: 1,
        name: "",
        date: "",
        price_origin: "",
      },
      row: "",
      rowNum: 1,
      page: {
        pageCurrent: 1,
        pageSize: 10,
        pageTotal: 0
      },
      markettableData: [],
      add_markettableData:[],
      edit_markettableData:[],
      ruleForm:{
        name:"",
        date:"",
        price:"",
        price_unit:"",
        price_origin:"",
      },
      rules: {
            name: [
              { required: true, message: '请输入现货行情名称', trigger: 'blur' },
            ],
            date: [
              { type: 'string', required: true, message: '请选择日期', trigger: 'change' },
            ],
            price: [
              { required: true, message: '请输入价格', trigger: 'blur' },
            ],
            price_unit: [
              { required: true, message: '请选择单位', trigger: 'change' },
            ],
            price_origin: [
              { required: true, message: '请输入来源', trigger: 'blur' },
            ],
      }
    };
  },
  created() {
           this.tabledatas.map(i => {
               i.show = false
               return i
           })
  },
  methods: {
    // 导入
     handleAvatarSuccess (res, file) {
        // this.uploadloading.close();
        console.log(444444,res.result);
        if (res && res.errcode === "1") {
           this.$message({
           message: '导入成功',
           type: 'success',
          })
          this.drmarketVisible = true;
          this.drmarkettableData = [];
          var data1 = res.result.Sheet1;
          for (var i = 0; i < data1.length; i++) {
            this.drmarkettableData[i] = {
               "name": data1[i].自定义现货行情名称,
               "date": data1[i].日期,
               "price": data1[i].价格,
               "price_unit": data1[i].单位,
               "price_origin": data1[i].来源
            }
          }
         
        } else {
          this.$message.error(res.msg);
        }
      },
      drmarket(){
        let params = { 
          "operation":"ADD",
          spot_market:this.drmarkettableData
        };
        addmarket(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                this.drmarketVisible = false;
                this.handle_marketChange();
            // } else {
            //     this.$message.error(res.msg);
            // }
             }).catch(err =>{
          this.$message.error(err.msg);
        });
      },
    // 每页数
    handleSizeChange(val) {
      this.marketForm.pageSize = val;
      this.marketForm.page = 1;
      this.handle_marketChange();
    },
    // 当前页
    handleCurrentChange1(val) {
      this.marketForm.page = val;
      this.handle_marketChange();
    },
     // 查询
    handle_marketChange(){
        // this.marketForm.page = 1;
        conmarket(this.marketForm).then(res => {
                this.markettableData = []
                var data = res.result.results;
                this.marketForm.totalPage = res.result.count;
                for (var i = 0; i < data.length; i++) {
                  this.markettableData = data
              }
             }).catch(err =>{
          this.$message.error(err.msg);
        });
    },
    //  新增
    addMarket(){
      this.marketVisible = true
    },
    // 新增保存
    addMarketChange(ruleForm){
      const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1]).then(() => {
       let params = {
           "operation":"ADD",
            "spot_market":this.add_markettableData
        };
        addmarket(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.marketVisible = false
                 this.handle_marketChange()
            // } else {
            //     this.$message.error(res.msg);
            // }
        }).catch(err =>{
          this.$message.error(err.msg);
        });
        });
    },
    //  修改
    editMarket(){
       if (this.multipleSelection == undefined) {
          this.openMessage();
      } else if(this.multipleSelection.length != 1){
         this.$message.error("修改只能选中一条数据进行！");
      } else {
         this. edit_marketVisible = true
         this.edit_markettableData = this.multipleSelection
      }
    },
    // 修改保存
    editMarketChange(){
       let params = {
           "operation":"MOD",
            "spot_market":{
              id: this.edit_markettableData[0].id,
              name: this.edit_markettableData[0].name,
              date: this.edit_markettableData[0].date,
              price: this.edit_markettableData[0].price,
              price_unit: this.edit_markettableData[0].price_unit,
              price_origin: this.edit_markettableData[0].price_origin,
            }
        };
        addmarket(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.edit_marketVisible = false
                 this.handle_marketChange()
            // } else {
            //     this.$message.error(res.msg);
            // }
             }).catch(err =>{
          this.$message.error(err.msg);
        });
    },
    
    //  删除
    delMarket(){
      this.$confirm('是否删除该自定义现货行情信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           var data = this.multipleSelection
           var currList  = [];
           data.forEach(function(item, index) {
              var data1 = item.id
              currList.push(data1)
              console.log(90,data1,91,currList)
          })
          let params = {
           "operation":"DEL",
           "spot_market":currList
        };
        addmarket(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.handle_marketChange()
            // } else {
            //     this.$message.error(res.msg);
            // }
         }).catch(err =>{
          this.$message.error(err.msg);
        });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 刷新
    handler_efreshCurrent(){
      this.marketForm.name = "",
      this.marketForm.date = "",
      this.marketForm.price_origin = "",
      this.handle_marketChange();
    },
     // 多选提示
    openMessage() {
      this.$message({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message: '<strong>请勾选你要选择的行，再进行操作！</strong>'
      });
    },
      // 行内编辑
    handleCellDataChange({ rowIndex, key, value, row }) {
      console.log(rowIndex);
      console.log(key);
      console.log(value);
      console.log(row);
    },
    // 多选
    handleSelectionChange(val) {
       this.multipleSelection = val;
       console.log('删除1',this.multipleSelection)
     },
     // 获取表格选中时的数据
      selectRow (val) {
        this.selectlistRow = val
      },
      // 增加行
      addRow () {
       	  var list = {
          rowNum:this.rowNum,
          name: "",
          date:"",
          price:"",
          price_origin:""
   		 };
        this.add_markettableData.unshift(list)
        this.rowNum += 1;
      },
      // 删除方法
      // 删除选中行
      delData() {
        console.log(12,this.selectlistRow)
        for (let i = 0; i < this.selectlistRow.length; i++) {
          let val = this.selectlistRow
          val.forEach((val, index) => {
            this.add_markettableData.forEach((v, i) => {
              if (val.rowNum === v.rowNum) {
                // i 为选中的索引
                this.add_markettableData.splice(i, 1)
              }
            })
          })
        }
        // 删除完数据之后清除勾选框
        this.$refs.table.clearSelection()
      },
    
  },
  mounted() {
      this.handle_marketChange();
  }
};
</script>
<style></style>
